<template>
  <div class="banner">
    <div class="banner">
      <swiper
        class="banner-swiper"
        :style="{ height }"
        :modules="modules"
        loop
        :autoplay="{ delay: 5000, disableOnInteraction: false }"
        :slides-per-view="1"
        :space-between="0"
        :pagination="{ clickable: true }"
        @swiper="onSwiper"
        @slideChange="onSlideChange"
      >
        <swiper-slide
          v-for="(item, index) in bannerData"
          :key="index"
        >
          <a
            v-if="item"
            :href="setBannerHref(item.href)"
          >
            <img :src="item.url" />
          </a>
        </swiper-slide>
      </swiper>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getBannerApi } from '@/service/common'

import { Swiper, SwiperSlide } from 'swiper/vue'
import { Autoplay, Pagination } from 'swiper'
import 'swiper/css/pagination'
import useLogin from '@/stores/login'
import { useRoute } from 'vue-router'

const storeLogin = useLogin()
const route = useRoute()

onBeforeMount(() => {
  init()
})

const { t, locale } = useI18n()
watch(locale, (n) => {
  init()
})

const props = defineProps({
  bannerModel: {
    type: String,
    default: '0'
  },
  height: {
    type: String,
    default: ''
  },
  isIndex: {
    type: Boolean,
    default: false
  }
})

// banner
const bannerData = ref([])
const myswiper = ref(null)
const onSwiper = (swiper) => {
  myswiper.value = swiper
}
const onSlideChange = () => {}
const modules = [Autoplay, Pagination]

// fn
const getBanner = () => {
  getBannerApi({
    bannerModel: props.bannerModel
  }).then(({ data }) => {
    if (!data) return
    const urlArr = data.bannerHref.split(',')
    bannerData.value = data.bannerImage.split(',').map((item, index) => {
      return {
        url: item,
        href: urlArr[index] || 'javascript:void(0)'
      }
    })

    if (props.isIndex) {
      bannerData.value = bannerData.value.slice(0, 3)
    }
  })
}

// 设置链接
const setBannerHref = (href) => {
  if (route.path === '/index') {
    // 首页 登录的跳个人中心
    return storeLogin?.userInfo?.id ? '#/personalHomepage' : href
  }
  return href
}

//
const init = () => {
  getBanner()
}

defineExpose({
  bannerData
})
</script>

<style scoped lang="scss">
.banner {
  :deep(.swiper-pagination-bullet) {
    width: 20px;
    height: 4px;
    border-radius: 0;
    background: rgba($color: #ffffff, $alpha: 1);
  }
  :deep(.swiper-pagination-bullet-active) {
    background: var(--mainColor);
  }

  .banner-swiper {
    .swiper-slide {
      height: auto;
      a {
        display: block;
        width: 100%;
        height: 100%;
      }
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
</style>
